package com.waymap.service.impl;


import com.alibaba.fastjson.JSONObject;

import com.waymap.common.Constant;
import com.waymap.domain.User;
import com.waymap.mapper.UserMapper;
import com.waymap.service.UserService;
import com.waymap.utils.AuthonTokenUtil;
import com.waymap.utils.CommonEnum;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.converter.MessageConversionException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.jms.JMSException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tim on 2018/7/18.
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public List<Map> getLocList(String available) {
        return userMapper.getLocList(available);
    }

    @Override
    public Map checkUserInfo(User user) {
        Map map = new HashMap();
        Map checkMap = userMapper.getUserInfo(user);
        if (checkMap == null) {
            map.put("result", new JSONObject());
            map.put("status", 400);
            map.put("msg", "用户名密码不匹配");
            return map;
        }
        Map subMap = new HashMap();
        subMap.put("id",checkMap.get("id"));
        subMap.put("subject",checkMap.get("user_name"));
        subMap.put("isssuer", Constant.ISSSUER);

        Map tokenMap = AuthonTokenUtil.createToken(subMap);
        /**把生成的token存进数据库**/
        int count = userMapper.updateUserToken(user.getUserName(), tokenMap.get("token").toString());
        if (count < -0) {
            map.put("status", 400);
            map.put("msg", "token更新失败");
            return map;
        }
        map.put("result", checkMap);
        map.put("status", CommonEnum.value("eSuccess"));
        map.put("msg", CommonEnum.value("eSMessage"));
        map.put("token", tokenMap.get("token"));
        map.put("limitedTime", tokenMap.get("limitedTime"));
        map.put("userId",checkMap.get("id"));

        return map;
    }

    /**
     * 修改密码
     *
     * @param userName
     * @param password
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Map> updateUserPassword(String userName, String password, String oldPassword) {
        Map map = new HashMap();

        User user = userMapper.getUserInfoByUserName(userName);
        if (null != user) {
            if (user.getPassword().equals(oldPassword)) {
                user.setPassword(password);
                int count = userMapper.updateByPrimaryKeySelective(user);
                if (count > 0) {
                    map.put("status", CommonEnum.value("eSuccess"));
                    map.put("msg", CommonEnum.value("eSMessage"));
                } else {
                    map.put("status", CommonEnum.value("eFail"));
                    map.put("msg", CommonEnum.value("eFailMessage"));
                }
            } else {
                map.put("status", CommonEnum.value("eFail"));
                map.put("msg", "密码错误");
            }
        } else {
            map.put("status", CommonEnum.value("eFail"));
            map.put("msg", "查询不到该用户名");
        }

        return ResponseEntity.ok(map);

    }

    /**
     * 通过token查询用户信息
     *
     * @param token
     * @return
     */
    @Override
    public User getUserInfoByToken(String token) {
    	User curUser =  userMapper.getUserInfoByToken(token);
    	System.out.println("current user:"+curUser);
    	return curUser;
    }

	@Override
	public ResponseEntity<Map> syncUser(Map userInfo) {
		// TODO Auto-generated method stub
		try {
			List<Map> result = userMapper.checkUserExist(userInfo);
			User u = new User();
			u.setUserName((String) userInfo.get("name"));
			u.setAccountId((String) userInfo.get("accountId"));
			u.setPassword((String) userInfo.get("passwd"));
			u.setLocationId(Integer.parseInt((String) userInfo.get("location")));
			if(result.size() > 0) {
				u.setId((int) result.get(0).get("id"));
				userMapper.updateByPrimaryKey(u);
			} else {
				userMapper.insert(u);
			}
			Map map = new HashMap();
			map.put("status", CommonEnum.value("eSuccess"));
	        map.put("msg", CommonEnum.value("eSMessage"));
			return ResponseEntity.ok(map);
		} catch(Exception e) {
			e.printStackTrace();
			Map map = new HashMap();
			map.put("status", CommonEnum.value("eFail"));
	        map.put("msg", e.getMessage());
			return ResponseEntity.ok(map);
		}
		
	}
}
